package com.fast.manager.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.fast.commons.spring.SpringContextHolder;
import com.fast.commons.utils.BeanUtils;
import com.fast.commons.web.model.AjaxResponse;
import com.fast.commons.web.model.DataGrid;
import com.fast.manager.system.domain.Menu;
import com.fast.manager.system.repository.MenuMapper;
import com.fast.manager.system.service.MenuPermitService;
import com.fast.manager.system.service.MenuService;

@Service
public class MenuServiceImpl implements MenuService {
	
	@Autowired
	private MenuMapper mapper ;

	@Autowired
	private MenuPermitService menuPermitService ;

	@CacheEvict(value="MenuCache", allEntries=true)
	@Override
	public AjaxResponse add(Menu record) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		
		if(this.mapper.existsFileldValue(null, "fullname", record.getFullName()) > 0) 
			return AjaxResponse.failMsg("该名称已存在！") ;
		if(this.mapper.existsFileldValue(null, "code", record.getCode()) > 0) 
			return AjaxResponse.failMsg("该权限代码已存在！") ;
		
		this.mapper.defaultSelect();
		
		record.setSortCode(this.mapper.nextSort(record.getPid(), record.getId())) ;
		this.mapper.insert(record) ;
		
		addPermit(record.getId(), record.getPermitIds());
		
		return ajaxResponse;
	}
	
	/**
	 * 添加权限
	 * @param resourceId
	 * @param permitIds
	 */
	private void addPermit(Long menu_id, String permitIds) {
		if(StringUtils.isNotBlank(permitIds)) {
			List<Long> permitIdsList = new ArrayList<Long>() ;
			String[] split = permitIds.split(",") ;
			for (String permitId : split) {
				permitIdsList.add(Long.parseLong(permitId));
			}
			this.menuPermitService.insertBatch(menu_id, permitIdsList);
		}
	}

	@CacheEvict(value="MenuCache", allEntries=true)
	@Override
	public AjaxResponse delete(long id) {
		del(this.mapper.selectByPrimaryKey(id));
		return SpringContextHolder.getBean(AjaxResponse.class).reset();
	}
	public void del(Menu record) {
		//删除资源关联的权限
		this.menuPermitService.deleteByMenuId(record.getId());
		
		List<Menu> rs = this.mapper.findMenuByCatalogId(record.getId().intValue()) ;
		if(null != rs && !rs.isEmpty()) {
			for (Menu resource : rs) {
				del(resource);
			}
		}
		this.mapper.deleteByPrimaryKey(record.getId()) ;
	}

	@Override
	public AjaxResponse deleteBatch(Long[] ids) {
		return null;
	}

	@CacheEvict(value="MenuCache", allEntries=true)
	@Override
	public AjaxResponse update(Menu record) {
		AjaxResponse ajaxResponse = SpringContextHolder.getBean(AjaxResponse.class).reset() ;
		
		if(this.mapper.existsFileldValue(record.getId(), "fullname", record.getFullName()) > 0) 
			return AjaxResponse.failMsg("该名称已存在！") ;
		if(this.mapper.existsFileldValue(record.getId(), "code", record.getCode()) > 0) 
			return AjaxResponse.failMsg("该权限代码已存在！") ;
		
		Menu menu = this.get(record.getId()) ;
		if (null != record.getPid() && !"".equals(record.getPid())) {
			if(menu.getId().equals(record.getPid())) {
				ajaxResponse.setStatus(false);
				ajaxResponse.setMessage("操作有误，父模块服务关联自己！");
				return ajaxResponse ;
			}
		}
		this.mapper.defaultSelect();
		this.mapper.updateByPrimaryKey(record);
		
		//删除资源关联的权限
		this.menuPermitService.deleteByMenuId(record.getId());
		addPermit(record.getId(), record.getPermitIds());
		return ajaxResponse;
	}

	@Cacheable(value="MenuCache" ,key="#root.targetClass +\".\"+ #root.methodName + (\"(\"+#id+\")\")")
	@Override
	public Menu get(long id) {
		return this.mapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Menu> getAllList(Menu record) {

		return null;
	}

	@Override
	public DataGrid<Menu> datagrid(Menu conditions) {

		return null;
	}
	
	@Cacheable(value="MenuCache" ,key="#root.targetClass +\".\"+ #root.methodName")
	@Override
	public List<Menu> findAllMenuByTopCatalog() {
		return this.mapper.findAllMenuByTopCatalog();
	}


	@Cacheable(value="MenuCache" ,key="#root.targetClass +\".\"+ #root.methodName")
	@Override
	public List<Menu> findMenuChildByCatalog() {
		List<Menu> menus = new ArrayList<Menu>() ;
		List<Menu> catalogList = this.findAllMenuByTopCatalog() ;
		for (Menu menu : catalogList) {
			menus.add(this.recursiveMenuCatalog(menu)) ;
		}
		return menus;
	}
	
	@Cacheable(value="MenuCache" ,key="#root.targetClass +\".\"+ #root.methodName + (\"(\"+#catalog_id+\")\")")
	@Override
	public List<Menu> findMenuChildrenByPid(Integer catalog_id) {
		List<Menu> menus = new ArrayList<Menu>() ;
		
		List<Menu> childrens = this.mapper.findMenuByCatalogId(catalog_id) ;
		for (Menu menu : childrens) {
			menus.add(this.recursiveMenu(menu)) ;
		}
		return menus ;
	}
	
	@Cacheable(value="MenuCache" ,key="#root.targetClass +\".\"+ #root.methodName")
	@Override
	public List<Menu> findAllMenuViewByTopCatalog() {
		List<Menu> catelogs = new ArrayList<Menu>() ;
		List<Menu> findAllMenuByTopCatalog = this.mapper.findAllMenuByTopCatalog() ;
		for (Menu menu : findAllMenuByTopCatalog) {
			Menu m = new Menu() ;
			BeanUtils.copyNotNullProperties(menu, m);
			m.setHref(menu.getLocation());
			m.setText(menu.getFullName());
			catelogs.add(m) ;
		}
		
		return catelogs ;
	}

	@Cacheable(value="MenuCache" ,key="#root.targetClass +\".\"+ #root.methodName + (\"(\"+#catalog_id+\")\")")
	@Override
	public List<Menu> findMenuChildrenViewByPid(Integer catalog_id) {
		List<Menu> menus = new ArrayList<Menu>() ;
		
		List<Menu> childrens = this.mapper.findMenuByCatalogId(catalog_id) ;
		for (Menu menu : childrens) {
			menus.add(this.recursiveMenu(menu)) ;
		}
		return menus ;
	}
	
	@Cacheable(value="MenuCache" ,key="#root.targetClass +\".\"+ #root.methodName")
	@Override
	public List<Menu> treegrid() {
		List<Menu> menus = new ArrayList<Menu>() ;
		List<Menu> catalogList = this.findAllMenuByTopCatalog() ;
		for (Menu menu : catalogList) {
			menus.add(this.recursiveMenu(menu)) ;
		}
		return menus;
	}
	
	/**
	 * 递归
	 * @param entity
	 * @return
	 */
	private Menu recursiveMenu(Menu entity) {
		entity.setHref(entity.getLocation());
		entity.setText(entity.getFullName());
		entity.setIconCls("icon-standard-application-view-list");
		List<Menu> childs = this.mapper.findMenuByCatalogId(entity.getId().intValue());
		if(null != childs && !childs.isEmpty()) {
			List<Menu> children = new ArrayList<Menu>() ;
			
			for (Menu r : childs) {
				if(null != r) {
					children.add(recursiveMenu(r)); 
				}
			}
			entity.setChildren(children);
		}
		return entity ;
	}
	
	/**
	 * 递归筛选目录
	 * @param entity
	 * @return
	 */
	private Menu recursiveMenuCatalog(Menu entity) {
		entity.setText(entity.getFullName());
		entity.setIconCls("icon-standard-application-view-list");
		
		List<Menu> childs = this.mapper.findMenuChildByCatalog(entity.getId().intValue());
		
		if(null != childs && !childs.isEmpty()) {
			List<Menu> children = new ArrayList<Menu>() ;
			
			for (Menu r : childs) {
				if(null != r) {
					children.add(recursiveMenuCatalog(r)); 
				}
			}
			entity.setChildren(children);
		}
		return entity ;
	}

	@Cacheable(value="MenuCache" ,key="#root.targetClass +\".\"+ #root.methodName + (\"(\"+#location+\")\")")
	@Override
	public Menu getLocation(String location) {
		Menu menu = this.mapper.getLocation(location) ;
		menu.setText(menu.getFullName());
		return menu;
	}

	@Cacheable(value="MenuCache" ,key="#root.targetClass +\".\"+ #root.methodName + (\"(\"+#id+\")\")")
	@Override
	public Menu getMenuByIdLinkPermit(Long id) {
		return this.mapper.getMenuByIdLinkPermit(id);
	}

	@Cacheable(value="MenuCache" ,key="#root.targetClass +\".\"+ #root.methodName + (\"(\"+#id+\")\")")
	@Override
	public Menu getMenuById(Long id) {
		return this.mapper.getMenuById(id);
	}



}
